package cn.com.jcoo;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.Locale;

@Slf4j
@Component
@RequiredArgsConstructor
public class I18nHelper {

	private static ResourceBundleMessageSource messageSource;
	private static HttpRequestLocaleResolver httpRequestLocaleResolver;

	@Autowired
	public void setMessageSource(ResourceBundleMessageSource messageSource) {
		I18nHelper.messageSource = messageSource;
	}

	@Autowired
	public void setHttpRequestLocaleResolver(HttpRequestLocaleResolver resolver) {
		I18nHelper.httpRequestLocaleResolver = resolver;
	}

	public static String getMessage(String code) {
		Locale locale = httpRequestLocaleResolver.getLocale();
		return getMessage(code, null, "", locale);
	}

	public static String getMessage(String code, String lang) {
		Locale locale;
		if (!StringUtils.hasLength(lang)) {
			locale = Locale.CHINA;
		}
		else {
			try {
				locale = new Locale(lang);
			}
			catch (Exception e) {
				locale = Locale.CHINA;
			}
		}
		return getMessage(code, null, code, locale);
	}

	public static String getMessage(String code, Object[] args, String defaultMessage,
			Locale locale) {
		String content;
		try {
			content = messageSource.getMessage(code, args, locale);
		}
		catch (Exception e) {
			log.error("国际化参数获取失败===>{}", e.getMessage(), e);
			content = defaultMessage;
		}
		return content;

	}
}
